import json
import logging
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from apps.services.dev_data_service import DevDataService,DevDataAnalysisService
from apps.serializers import TDevDataSerializer
from apps.utils.response_utils import success_response, error_response

@method_decorator(csrf_exempt, name='dispatch')
class DevDataView(View):
    """
    DevData 视图类
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.dev_data_service = DevDataService()
        self.serializer = TDevDataSerializer()

    def get(self, request, pk=None):
        """
        处理GET请求
        """
        try:
            if pk:
                # 获取单个设备数据记录
                dev_data = self.dev_data_service.get_dev_data_by_id(pk)
                if dev_data:
                    serialized_data = self.serializer.serialize(dev_data)
                    return success_response(data=serialized_data)
                else:
                    return error_response('设备数据记录不存在')
            else:
                # 获取所有设备数据记录
                dev_data_list = self.dev_data_service.get_all_dev_data()
                serialized_data = self.serializer.serialize_list(dev_data_list)
                return success_response(serialized_data)
        except Exception as e:
            return error_response(str(e))

    def post(self, request):
        """
        处理POST请求，创建新的设备数据记录
        """
        try:
            # 判断内容类型并相应处理
            if request.content_type == 'application/json':
                data = json.loads(request.body.decode('utf-8'))
            else:
                # 假设是表单数据
                data = request.POST
            # 这里应该从请求中获取数据，为了简化示例，使用默认值
            data_type = data.get('data_type', '')
            data_id = int(data.get('data_id', 0))
            dev_id = int(data.get('dev_id', 0))
            reg_id = int(data.get('reg_id', 0))
            data_value = float(data.get('data_value', 0.0))
            data_time = data.get('data_time', '')

            dev_data = self.dev_data_service.create_dev_data(
                data_type=data_type,
                data_id=data_id,
                dev_id=dev_id,
                reg_id=reg_id,
                data_value=data_value,
                data_time=data_time
            )

            serialized_data = self.serializer.serialize(dev_data)
            return success_response(data=serialized_data)
        except ValueError as e:
            return error_response(str(e))
        except Exception as e:
            return error_response(str(e))

    def put(self, request, pk):
        """
        处理PUT请求，更新设备数据记录
        """
        try:
            # 获取要更新的数据
            update_data = {}
            data_type = request.POST.get('data_type')
            if data_type is not None:
                update_data['data_type'] = data_type

            data_id = request.POST.get('data_id')
            if data_id is not None:
                update_data['data_id'] = int(data_id)

            dev_id = request.POST.get('dev_id')
            if dev_id is not None:
                update_data['dev_id'] = int(dev_id)

            reg_id = request.POST.get('reg_id')
            if reg_id is not None:
                update_data['reg_id'] = int(reg_id)

            data_value = request.POST.get('data_value')
            if data_value is not None:
                update_data['data_value'] = float(data_value)

            data_time = request.POST.get('data_time')
            if data_time is not None:
                update_data['data_time'] = data_time

            dev_data = self.dev_data_service.update_dev_data(pk, **update_data)
            if dev_data:
                serialized_data = self.serializer.serialize(dev_data)
                return success_response(data=serialized_data)
            else:
                return success_response(data=None,msg='设备数据记录不存在')
        except ValueError as e:
            return error_response(str(e))
        except Exception as e:
            return error_response(str(e))

    def delete(self, request, pk):
        """
        处理DELETE请求，删除设备数据记录
        """
        try:
            result = self.dev_data_service.delete_dev_data(pk)
            if result:
                return success_response(data=None,msg='设备数据记录删除成功')
            else:
                return success_response(data=None,msg='设备数据记录不存在')
        except Exception as e:
            return error_response(str(e))

@method_decorator(csrf_exempt, name='dispatch')
class DevDataAnalysisView(View):
    """
    设备采集数据视图类
    """
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.dev_data_service = DevDataService()
        self.dev_data_analysis_service = DevDataAnalysisService()

    def post(self, request):
        """
        处理POST请求
        """
        try:
            # 判断内容类型并相应处理
            if request.content_type == 'application/json':
                data = json.loads(request.body.decode('utf-8'))
            else:
                # 假设是表单数据
                data = request.POST
            dev_ids = data.get('dev_ids', [])
            start_time = data.get('start_time', None)
            end_time = data.get('end_time', None)
            space = data.get('space', None)
            self.dev_data_analysis_service.analysis_dev_datas(dev_ids, start_time, end_time, space)
            return success_response()
        except Exception as e:
            print(e)
            return error_response(str(e))

@method_decorator(csrf_exempt, name='dispatch')
class GetDevDataView(View):
    """
    查询设备采集数据
    """
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.dev_data_service = DevDataService()
        self.dev_data_analysis_service = DevDataAnalysisService()

    def get(self, request):
        try:
            data_type = request.GET.get('data_type', None)
            dev_id = request.GET.get('dev_id', None)
            start_time = request.GET.get('start_time', None)
            end_time = request.GET.get('end_time', None)

            # 如果传入的是字符串形式的数字，转换为整数
            if dev_id is not None:
                try:
                    dev_id = int(dev_id)
                except ValueError:
                    return error_response("dev_id必须是整数")

            dev_data_list = self.dev_data_service.get_dev_data_by_condition(data_type,dev_id, start_time, end_time)
            return success_response(data=dev_data_list)
        except Exception as e:
            self.logger.error(str(e))
            return error_response(str(e))